<template>
  <div class="resource-content">
    <div class="search-section">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索资源标题或描述..."
          clearable
          style="width: 300px;"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button
          type="primary"
          @click="handleSearch"
          style="margin-left: 10px;"
      >
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
    </div>
    <!-- 顶部按钮式选项卡 -->
    <div class="content-tabs">
      <el-button
          v-for="tab in resourceTypes"
          :key="tab.id"
          :type="activeResourceType === tab.sortOrder ? 'primary' : ''"
          @click="changeResourceType(tab.sortOrder)"
          class="tab-button"
      >
        {{ tab.name }}
      </el-button>
    </div>

    <!-- 文件列表 -->
    <div class="file-list">
      <div v-if="loading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>资源加载中...</span>
      </div>

      <div v-else-if="resources.length === 0" class="empty">
        <p>暂无资源</p>
        <p class="empty-subtext">当前分类下还没有资源内容，请稍后再来看看</p>
        <div class="empty-actions">
          <!--          <el-button type="primary" size="small" @click="refreshPage">-->
          <!--            刷新页面-->
          <!--          </el-button>-->
          <!--          <el-button size="small" @click="goBack">-->
          <!--            返回上一级-->
          <!--          </el-button>-->
        </div>
      </div>

      <div v-else>
        <div
            v-for="resource in paginatedResources"
            :key="resource.id"
            class="file-item"
        >
          <div class="file-icon">
            <el-icon :size="24">
              <component :is="getFileIcon(resource.typeId)" />
            </el-icon>
          </div>
          <div class="file-info">
            <div class="file-name">{{ resource.title }}</div>
            <div class="file-meta">
              <span class="file-type">{{ getTypeName(resource.typeId) }}</span>
              <span class="file-size">{{ resource.fileSize }}</span>
              <span class="file-date">{{ formatDate(resource.createdAt) }}</span>
            </div>
            <div v-if="resource.description" class="file-description">
              {{ resource.description }}
            </div>
          </div>
          <div class="file-actions">
            <el-button type="primary" size="small" @click="downloadResource(resource)">
              下载
            </el-button>
            <el-button size="small" @click="previewResource(resource)">
              预览
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="resources.length > 0" class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="resources.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import {
  Document,
  Picture,
  VideoPlay,
  Collection,
  Notebook,
  Tickets,
  Postcard,
  Loading, Search
} from '@element-plus/icons-vue';
import { fetchResourceTypes, fetchResources } from "@/api/teacher";

const props = defineProps({
  subcategoryId: {
    type: Number,
    required: true, // 新增
  }
});

// 资源类型和资源数据
const resourceTypes = ref<any[]>([]);
const resources = ref<any[]>([]);
const loading = ref(false);
const searchKeyword = ref('')
// 当前激活的资源类型 (使用id而不是code)
const activeResourceType = ref(0); // 0表示"全部"

// 分页设置
const currentPage = ref(1);
const pageSize = ref(10);

// 加载资源类型
const loadResourceTypes = async () => {
  try {
    const res = await fetchResourceTypes();
    if (res.success) {
      resourceTypes.value = res.data;
    }
  } catch (error) {
    console.error('加载资源类型失败:', error);
  }
};

// 加载资源数据
const loadResources = async () => {
  if (!props.subcategoryId) return;

  loading.value = true;
  try {
    const params = {
      subcategoryId: props.subcategoryId,
      typeId: Number(activeResourceType.value) === 0 ? 0 :Number(activeResourceType.value) + 1,
      keyword: searchKeyword.value
    };
    const res = await fetchResources(params);
    if (res.success) {
      resources.value = res.data;
    } else {
      console.error('资源加载失败:', res.message);
    }
  } catch (error) {
    console.error('加载资源失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索方法 - 只有在点击搜索按钮时触发
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  loadResources();
};

// 监听subcategoryId变化
watch(() => props.subcategoryId, (newVal) => {
  if (newVal) {
    currentPage.value = 1;
    loadResources();
  }
});

// 监听资源类型变化
watch(activeResourceType, (newVal) => {
  currentPage.value = 1;
  loadResources();
});

// 分页后的资源列表
const paginatedResources = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return resources.value.slice(start, end);
});

// 修正：根据typeId获取对应的图标
const getFileIcon = (typeId: number) => {
  const typeMap: { [key: number]: any } = {
    0: Collection,     // 课件 (document)
    1: Document,     // 课件 (document)
    2: Tickets,      // 试卷 (exam)
    3: Postcard,     // 导学案 (guide)
    4: Notebook,     // 教案 (lesson_plan)
    5: Picture,      // 素材 (material)
    6: VideoPlay     // 微课 (micro_course)
  };
  return typeMap[typeId] || Document;
};

// 修正：根据typeId获取类型名称
const getTypeName = (typeId: number) => {
  const type = resourceTypes.value.find(t => t.id === typeId);
  return type ? type.name : '未知类型';
};

// 格式化日期
const formatDate = (dateString: string) => {
  try {
    return new Date(dateString).toLocaleDateString('zh-CN');
  } catch {
    return '未知日期';
  }
};

// 切换资源类型
const changeResourceType = (typeId: number) => {
  console.log(typeId)
  activeResourceType.value = typeId;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

// 下载资源
const downloadResource = (resource: any) => {
  if (resource.fileUrl) {
    window.open(resource.fileUrl, '_blank');
  } else {
    console.warn('资源没有文件URL');
  }
};

// 预览资源
const previewResource = (resource: any) => {
  // 这里可以添加预览逻辑
};

// 初始化加载
onMounted(() => {
  loadResourceTypes();
  if (props.subcategoryId) {
    loadResources();
  }
});
</script>

<style scoped>
.resource-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 搜索区域样式调整 */
.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

/* 内容选项卡样式 */
.content-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.content-tabs .el-button {
  border-radius: 16px;
  padding: 8px 15px;
}

/* 文件列表样式 */
.file-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 15px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.file-item:hover {
  background-color: #f9fafc;
}

.file-icon {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: #1e62ec;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.file-type, .file-size, .file-date {
  display: flex;
  align-items: center;
}

.file-actions {
  display: flex;
  gap: 8px;
}

/* 加载状态样式 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.loading .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409eff;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 空状态样式 - 美化暂无资源显示 */
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  text-align: center;
  color: #909399;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  margin: 20px;
  padding: 40px 20px;
}

.empty::before {
  content: "📁";
  font-size: 64px;
  margin-bottom: 20px;
  display: block;
}

.empty p {
  font-size: 16px;
  margin: 0 0 10px 0;
  color: #606266;
  font-weight: 500;
}

.empty .empty-subtext {
  font-size: 14px;
  color: #909399;
  margin: 0;
  line-height: 1.5;
  max-width: 300px;
}

.empty .empty-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

/* 文件描述样式 */
.file-description {
  font-size: 13px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-section .el-input {
    width: 100% !important;
  }

  .search-section .el-button {
    margin-left: 0 !important;
    width: 100%;
  }

  .content-tabs {
    gap: 5px;
  }

  .content-tabs .el-button {
    padding: 6px 10px;
    font-size: 13px;
  }

  .file-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px;
  }

  .file-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .file-info {
    width: 100%;
    margin-bottom: 10px;
  }

  .file-actions {
    width: 100%;
    justify-content: flex-end;
  }

  /* 移动端空状态调整 */
  .empty {
    height: 250px;
    margin: 15px;
    padding: 30px 15px;
  }

  .empty::before {
    font-size: 48px;
    margin-bottom: 15px;
  }

  .empty p {
    font-size: 15px;
  }

  .empty .empty-subtext {
    font-size: 13px;
    max-width: 250px;
  }
}
</style>
